/*
 * 文 件 名 : ApplyServerActivity.java
 * 版    权 : China Machi.Co.,Ltd.Copyright 2009-2011.All rights reserved
 * 描    述 : <描述>
 * 修 改 人 : lixg
 * 修改时间 : 2012-11-22
 * 跟踪单号 : <跟踪单号>
 * 修改单号 : <修改单号>
 * 修改内容 : <修改内容>
 */
package com.fire8.dolphin.ui.more;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.fire8.dolphin.model.UserInfo;
import com.fire8.dolphin.ui.DolphinApplication;
import com.fire8.dolphin.ui.R;
import com.fire8.dolphin.utils.Base64Coder;
import com.fire8.dolphin.utils.LogUtil;
import com.fire8.dolphin.utils.StringUtil;
import com.fire8.dolphin.web.RequestUtils;

/**
 * 申请成为咨询师
 * <功能详细描述>
 *
 * @author  lixg
 * @version [版本号,2012-11-22]
 * @see     [相关类/方法]
 * @since   [产品/模块]
 */
public class ApplyServerActivity extends Activity
{
    private EditText txtUserName;
    private EditText txtMobile;
    private EditText txtIdCard;
    private ImageView imgIdCard;
    private ImageView imgWorkCard;
    private Button btnEnter;
    
    private String strUserName;
    private String strMobile;
    private String strIdCard;
    
    private boolean success;
    private UserInfo user;
    private DolphinApplication app;
    private ProgressDialog progressDialog = null;
    private StringBuffer url = new StringBuffer(DolphinApplication.URL);
    private String[] items = new String[] { "选择本地图片", "拍照" };
    
    /*身份证图片名称*/
    private static final String IMA_IDCARD_NAME = "idcard.jpg";
    /*工作证图片名称*/
    private static final String IMA_WORK_CARD_NAME = "workcard.jpg";
    
    /* 请求码*/
    private static final int IMAGE_REQUEST_CODE_IC = 0;
    private static final int IMAGE_REQUEST_CODE_WC = 1;
    
    private static final int CAMERA_REQUEST_CODE_IC = 2;
    private static final int CAMERA_REQUEST_CODE_WC = 3;
    
    private static final int RESULT_REQUEST_CODE = 2;
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.apply_server);
        app = (DolphinApplication)getApplication();
        txtUserName = (EditText)findViewById(R.id.txt_user_name);
        txtMobile = (EditText)findViewById(R.id.txt_mobile);
        txtIdCard = (EditText)findViewById(R.id.txt_idcard);
        imgIdCard = (ImageView)findViewById(R.id.img_idcard);
        imgWorkCard = (ImageView)findViewById(R.id.img_work_card);
        btnEnter = (Button)findViewById(R.id.btn_enter);
        setElementEvent();
        
    }
    private void setElementEvent()
    {
        
        btnEnter.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                strUserName = txtUserName.getText().toString();
                strMobile = txtMobile.getText().toString();
                strIdCard = txtIdCard.getText().toString();
                if(StringUtil.isEmpty(strUserName) || StringUtil.isEmpty(strMobile)|| StringUtil.isEmpty(strIdCard))
                {
                    Toast.makeText(ApplyServerActivity.this, "请填写完整", Toast.LENGTH_LONG).show();
                    return;
                }
                if(imgIdCard.getTag() == null)
                {
                    Toast.makeText(ApplyServerActivity.this, "请上传身份证照片或复印件", Toast.LENGTH_LONG).show();
                    return;
                }
                if(imgWorkCard.getTag() == null)
                {
                    Toast.makeText(ApplyServerActivity.this, "请上传上岗证照片或复印件", Toast.LENGTH_LONG).show();
                    return;
                }
                if(StringUtil.isEmpty(app.getUserId()))
                {
                    Toast.makeText(ApplyServerActivity.this, "您未注册，请先注册再修改", Toast.LENGTH_LONG).show();
                    return;
                }
                user = new UserInfo();
                user.setUserId(Integer.valueOf(app.getUserId()));
                user.setAccount(app.getAccount());
                //user.setPassword();
                user.setRealName(strUserName);
                user.setMobile(strMobile);
                user.setIdCard(strIdCard);
                //getResources().geti
                
                //打开进度条窗口
                progressDialog = ProgressDialog.show(ApplyServerActivity.this, "请稍等...", "正在提交...", true);
                //执行提交任务
                new RegisterTask().execute(user);
            }
        });
        imgIdCard.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                showDialog(IMA_IDCARD_NAME);
            }
        });
        imgWorkCard.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                showDialog(IMA_WORK_CARD_NAME);
            }
        });
        
    }
    
    /**
     * 提交申请
     * <功能详细描述>
     *
     * @author  lixg
     * @version [版本号,2012-11-22]
     * @see     [相关类/方法]
     * @since   [产品/模块]
     */
    class RegisterTask extends AsyncTask<UserInfo, Void, String>
    {
        @Override
        protected String doInBackground(UserInfo... params)
        {
            if(!RequestUtils.getInstall().isConnect(ApplyServerActivity.this))
            {
                return "网络不可用";
            }
            try
            {
                UserInfo user = params[0];
                List<NameValuePair> param = new ArrayList<NameValuePair>();
                param.add(new BasicNameValuePair("userId",String.valueOf(user.getUserId())));
                param.add(new BasicNameValuePair("account",user.getAccount()));
                param.add(new BasicNameValuePair("realName",user.getRealName()));
                param.add(new BasicNameValuePair("mobile",user.getMobile()));
                param.add(new BasicNameValuePair("idcard",user.getIdCard()));
                param.add(new BasicNameValuePair("imgIdcard",(String)imgIdCard.getTag()));
                param.add(new BasicNameValuePair("imgWorkCard",(String)imgWorkCard.getTag()));
                String json = RequestUtils.getInstall().getHttpJson(url.append("user/updateUserInfo.php").toString(), param);
                LogUtil.d(json);
                if(!StringUtil.isEmpty(json))
                {
                    try
                    {
                        JSONObject data = new JSONObject(json);
                        String msgCode = data.getString("msgCode");
                        String desc = data.getString("desc");
                        
                        if("1".equals(msgCode))
                        {
                            success=true;
                        }else
                        {
                            LogUtil.d(desc);
                            return desc;
                        }
                    }
                    catch (JSONException e)
                    {
                        LogUtil.e("" ,e);
                    }
                }
                return json;
            }
            catch (Exception e)
            {
                LogUtil.e("" ,e);
                return "请求失败，请稍候再试";
            }
            
        }
        @Override
        protected void onPostExecute(String result)
        {
            super.onPostExecute(result);
            progressDialog.dismiss();
            if(!success)
            {
                Toast.makeText(ApplyServerActivity.this, result, Toast.LENGTH_LONG).show();
                return;
            }else
            {
                //如果修改成功，将窗口关闭
                ApplyServerActivity.this.finish();
            }
            
        }
    }
    
    /** 弹出对话框获取图片*/
    private void showDialog(final String fileName) 
    {
        new AlertDialog.Builder(this)
        .setTitle("上传图片")
        .setItems(items, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                        case 0:
                                Intent intentFromGallery = new Intent();
                                intentFromGallery.setType("image/*"); // 设置文件类型
                                intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
                                if(IMA_IDCARD_NAME.equals(fileName))
                                {
                                    startActivityForResult(intentFromGallery,IMAGE_REQUEST_CODE_IC);
                                }else
                                {
                                    startActivityForResult(intentFromGallery,IMAGE_REQUEST_CODE_WC);
                                }
                                
                                break;
                        case 1:

                                Intent intentFromCapture = new Intent(
                                                MediaStore.ACTION_IMAGE_CAPTURE);
                                // 判断存储卡是否可以用，可用进行存储
                                if (hasSdcard()) {
                                        intentFromCapture.putExtra(
                                                        MediaStore.EXTRA_OUTPUT,
                                                        Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                                                                fileName)));
                                }
                                if(IMA_IDCARD_NAME.equals(fileName))
                                {
                                    startActivityForResult(intentFromCapture,CAMERA_REQUEST_CODE_IC);
                                }else
                                {
                                    startActivityForResult(intentFromCapture,CAMERA_REQUEST_CODE_WC);
                                }
                                
                                break;
                        }
                }
        })
        .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                }
        }).show();
    }
    
    /** 检查内存卡是否可用 */
    private boolean hasSdcard()
    {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (resultCode == RESULT_CANCELED)
        {
            return;
        }
        switch (requestCode)
        {
            case IMAGE_REQUEST_CODE_IC:
                
                getImageToView(data.getData(), imgIdCard);
                break;
            case IMAGE_REQUEST_CODE_WC:
                
                getImageToView(data.getData(), imgWorkCard);
                break;
            case CAMERA_REQUEST_CODE_IC:
                
                if (hasSdcard()) {
                    File tempFile = new File(Environment.getExternalStorageDirectory(),IMA_IDCARD_NAME);
                    LogUtil.d(tempFile.getName());
                    getImageToView(Uri.fromFile(tempFile),imgIdCard);
                } else {
                        Toast.makeText(this, "未找到存储卡，无法存储照片！",Toast.LENGTH_LONG).show();
                }
                
                break;
            case CAMERA_REQUEST_CODE_WC:
                
                if (hasSdcard()) {
                    File tempFile = new File(Environment.getExternalStorageDirectory(),IMA_WORK_CARD_NAME);
                    LogUtil.d(tempFile.getName());
                    getImageToView(Uri.fromFile(tempFile),imgWorkCard);
                } else {
                        Toast.makeText(this, "未找到存储卡，无法存储照片！",Toast.LENGTH_LONG).show();
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    
    /**
     * 保存裁剪之后的图片数据
     * 
     * @param picdata
     */
    private void getImageToView(Uri uri,ImageView imgView) {
        Bitmap photo=null;
        
        if (uri != null) {
            //LogUtil.d("uri:"+uri.toString());
            ContentResolver cr = this.getContentResolver(); 
            try
            {
                photo = BitmapFactory.decodeStream(cr.openInputStream(uri));
            }
            catch (FileNotFoundException e)
            {
                LogUtil.e("文件没找到",e);
            }
            
        }
        if(photo != null)
        {
            Drawable drawable = new BitmapDrawable(photo);
            imgView.setImageDrawable(drawable);
            LogUtil.d("设置ImageView");
            /**  
             * 下面方法是将裁剪之后的图片以Base64Coder的字符方式上  
             * 传到服务器，QQ头像上传采用的方法跟这个类似  
             */ 
            ByteArrayOutputStream stream = new ByteArrayOutputStream();  
            photo.compress(Bitmap.CompressFormat.JPEG, 60, stream);  
            byte[] b = stream.toByteArray();  
            // 将图片流以字符串形式存储下来  
            imgView.setTag(new String(Base64Coder.encodeLines(b)));  
        }
            
    }
}
